/**
 * @author yxw
 * date : 2013年9月30日 下午3:43:33 
 */
package com.tzinfo.tzt.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.ConvertSwitch;
import com.tzinfo.tzt.activity.util.GPSThread;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.activity.view.ImageAdapter;
import com.tzinfo.tzt.activity.view.MyProgressDialog;
import com.tzinfo.tzt.activity.view.XListView;
import com.tzinfo.tzt.activity.view.XListView.IXListViewListener;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.config.FilterConfig;
import com.tzinfo.tzt.domain.LocationGeocoder;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.NewhouseList;
import com.tzinfo.tzt.domain.OldhouseList;
import com.tzinfo.tzt.domain.RenthouseList;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;

public class RentHouseLocalActivity extends BaseActivity implements
		IXListViewListener, OnClickListener, OnItemClickListener {

	private Button btnBack;
	private Button btnPositioning;
	private LinearLayout layoutConstraint;
	private TextView localText, titleText;

	private XListView xListView;
	private SimpleAdapter simpleAdapter;

	private List<Map<String, Object>> data;
	private List<Object> houseList;
	private Handler mHandler;

	protected int locationCode = 0;
	protected LocationGeocoder geocoder;
	private Location location = MyApplication.location;

	private ImageAdapter imageAdapter;

	// 标志
	private int attrType = 0;

	private MyResultList rentHouseListResult;

	static String sID = "sID";
	static String sStyle = "Style";
	static String sLogo = "Logo";
	static String sName = "Name";
	static String sAddress = "Address";
	static String sSize = "Size";
	static String sPrice = "Price";
	private int pageNum = 1;
	private static final int pageSize = 10;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_local_house);
		mProgressBar = (ProgressBar)findViewById(R.id.progressbar_loding);
		showProgressBar();
		new Thread(getLocationAddressRun).start();// 定位
		init();
	}

	private void checkLocation() {
//		if ("外地".equals(FilterConfig.FILTER_CONTENT[0][MyApplication.nowLocationCode])) {
//			Toast.makeText(this, "您当前不在台州地区！", 5000).show();
//			// this.finish();
//		}
	}

	private void setLocalData() {
		localText.setText("当前位置：" + geocoder.getStreet() + "附近");
	}

	private void init() {
		mHandler = new Handler();
		xListView = (XListView) findViewById(R.id.xListView_local);
		xListView.setPullRefreshEnable(false);
		xListView.setPullLoadEnable(true);
		xListView.setVisibility(View.GONE);
		xListView.setAdapter(simpleAdapter);
		// xListView.setPullLoadEnable(false);
		// xListView.setPullRefreshEnable(false);
		xListView.setXListViewListener(this);
		xListView.setOnItemClickListener(this);
		localText = (TextView) this.findViewById(R.id.text_local);
		titleText = (TextView) this.findViewById(R.id.text_title);
		titleText.setText("附近租房");

		btnBack = (Button) this.findViewById(R.id.bt_back);
		btnBack.setOnClickListener(this);
		btnPositioning = (Button) this.findViewById(R.id.bt_positioning);
		btnPositioning.setOnClickListener(this);
		layoutConstraint = (LinearLayout) this
				.findViewById(R.id.layout_constraint);
		layoutConstraint.setVisibility(View.GONE);
		// layoutConstraint.setOnClickListener(this);
	}

	private void newAdapter() {
		// 自定义的图片适配器
		imageAdapter = new ImageAdapter(this, data, R.layout.item_main_list,
				new String[] { sLogo, sName, sAddress, sSize, sPrice, sID },
				new int[] { R.id.list_item_image, R.id.list_item_title,
						R.id.list_item_address, R.id.list_item_size,
						R.id.list_item_price, R.id.un_house_id });
	}

	private void updateUI() {
		newAdapter();
		// xListView.setAdapter(simpleAdapter);
		xListView.setAdapter(imageAdapter);
		xListView.setVisibility(View.VISIBLE);
	}

	/**
	 * 将得到的数据装载进ArrayList<Map<String, Object>>() data中
	 */
	private void getData() {
		data = new ArrayList<Map<String, Object>>();
		RenthouseList rentListItem;
		Map<String, Object> map;
		if (rentHouseListResult.getSuccess()) {
			houseList=rentHouseListResult.getData();
			for (int i = 0; i < rentHouseListResult.getData().size(); i++) {
				rentListItem = (RenthouseList) rentHouseListResult.getData()
						.get(i);
				map = new HashMap<String, Object>();
				map.put(sLogo, rentListItem.getLogo());
				String strName = rentListItem.getName();
				if (strName.length() > 9) {
					strName = strName.substring(0, 9) + "…";
				}
				map.put(sName, strName);
				String strAddress = rentListItem.getAddress();
				if (strAddress.length() > 20) {
					strAddress = strAddress.substring(0, 20) + "…";
				}
				map.put(sAddress, strAddress);
				map.put(sSize, rentListItem.getStyle());
				String price = rentListItem.getPrice();
				if ("0元".equals(price)) {
					price = "售价待定";
				} else {
					price += "/" + rentListItem.getPriceUnit();
				}
				map.put(sPrice, price);
				map.put(sID, rentListItem.getID());
				data.add(map);
			}
		}
	}

	private void getMoreData() {
		RenthouseList rentListItem;
		Map<String, Object> map;
		if (rentHouseListResult.getSuccess()) {

			for (int i = 0; i < rentHouseListResult.getData().size(); i++) {
				houseList.add(rentHouseListResult.getData().get(i));
				rentListItem = (RenthouseList) rentHouseListResult.getData()
						.get(i);
				map = new HashMap<String, Object>();
				map.put(sLogo, rentListItem.getLogo());
				String strName = rentListItem.getName();
				if (strName.length() > 8) {
					strName = strName.substring(0, 9) + "…";
				}
				map.put(sName, strName);
				String strAddress = rentListItem.getAddress();
				if (strAddress.length() > 20) {
					strAddress = strAddress.substring(0, 20) + "…";
				}
				map.put(sAddress, strAddress);
				map.put(sSize, rentListItem.getStyle());
				String price = rentListItem.getPrice();
				if ("0元".equals(price)) {
					price = "售价待定";
				} else {
					price += "/" + rentListItem.getPriceUnit();
				}
				map.put(sPrice, price);
				map.put(sID, rentListItem.getID());
				data.add(map);
			}
		}
	}

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						GPSThread.getInstance(RentHouseLocalActivity.this).requestLocation();
						showProgressBar();
						new Thread(getLocationAddressRun).start();
					}
				}).show();
	}

	@SuppressLint("HandlerLeak")
	Handler locationHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				// if (geocoder.getCityCode() == 244) {
				locationCode = 0;
				while (locationCode < FilterConfig.FILTER_CONTENT[0].length
						&& !geocoder.getDistrict().equals(
								FilterConfig.FILTER_CONTENT[0][locationCode])) {
					locationCode++;
				}
				if (locationCode == FilterConfig.FILTER_CONTENT[0].length) {
					MyApplication.nowLocationCode = locationCode - 1;
					locationCode = 1;
				} else {
					MyApplication.nowLocationCode = locationCode;
				}
				checkLocation();
				setLocalData();
				initData();
				break;
			case -1:
				getDataError((String) msg.obj);
				break;
			case 0:
				break;
			}
		}
	};

	protected void showLastRow() {
		Toast.makeText(this, "已经是最后一页！", Toast.LENGTH_SHORT).show();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case -1:
				getDataError((String) msg.obj);
				break;
			case 1:
				updateUI();
				if (xListView.getFooterViewsCount() == 0) {
					xListView.addFooterView(xListView.getmFooterView());
				}
				removeProgressBar();
				onLoad();
				break;
			case 2:
				if (xListView.getFooterViewsCount() == 0) {
					xListView.addFooterView(xListView.getmFooterView());
				}
				imageAdapter.notifyDataSetChanged();
				onLoad();
				break;
			case 3:
				// 最后一页
				showLastRow();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				onLoad();
				break;
			case 4:
				// 没有数据
				updateUI();
				data.clear();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				imageAdapter.notifyDataSetChanged();
				// xListView.setVisibility(View.GONE);
				removeProgressBar();
				onLoad();
				break;
			case 5:
				// 只有一页
				updateUI();
				onLoad();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				removeProgressBar();
				break;
			case 0:
				break;
			}
		}
	};
	/**
	 * 线程 得地理位置
	 */
	Runnable getLocationAddressRun = new Runnable() {

		@Override
		public void run() {
			Message msg = locationHandler.obtainMessage();
			String url="";
			String jsonString="";
			if(location!=null){
				url = AppDataConfig.baiduGeoUrl + "?ak="
						+ AppDataConfig.baiduak + "&callback=renderReverse&"
						+ "location=" + location.getLatitude() + ","
						+ location.getLongitude() + "&output=json&pois=0";
				Log.e("baidu", url);
				jsonString = HttpTools.getJsonContent(url);
				Log.e("JsonString", jsonString);
				geocoder = JsonTools.getLocationToAddress(jsonString);
			}
			if (location!=null&&geocoder.getStatus() == 0) {
				msg.arg1 = 1;
			} else {
				msg.arg1 = -1;
				if(geocoder!=null){
					msg.obj = geocoder.getErrorMessage();
				}else{
					msg.obj = "定位失败，请检查您的GPS和网络！";
				}
				
			}
			locationHandler.sendMessage(msg);
		}
	};

	private void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		xListView.setRefreshTime(df.format(new Date()));
	}

	private void initData() {
		pageNum = 1;
		// 通过线程访问网络得到数据
		new Thread(getRentHouseListResultRun).start();
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				pageNum = 1;
				initData();

			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				pageNum++;
				new Thread(getMoreRentHouseListResultRun).start();

			}
		}, 2000);
	}

	/**
	 * 线程 得到租房列表
	 */
	Runnable getRentHouseListResultRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String sFilter = "?listtype=2" + ConvertSwitch.ConvertBD09ToGCJ02String(geocoder.getLat(),geocoder.getLng())
					+ "&pagenumber=" + pageNum + "&pagesize=" + pageSize;
			Log.e("url", AppDataConfig.zufangUrl
					+ AppDataConfig.RenthouseList + sFilter);
			jsonString = HttpTools.getJsonContent(AppDataConfig.zufangUrl
					+ AppDataConfig.RenthouseList + sFilter);
			Log.e("JsonString", jsonString);
			rentHouseListResult = JsonTools.getRenthouseList(jsonString);
			getData();
			if (rentHouseListResult.getSuccess()) {
				if (rentHouseListResult.getData().size() == 0) {
					msg.arg1 = 4;
				} else if (rentHouseListResult.getData().size() < pageSize) {
					msg.arg1 = 5;
				} else {
					msg.arg1 = 1;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = rentHouseListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};
	/**
	 * 线程 得到新房列表
	 */
	Runnable getMoreRentHouseListResultRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String sFilter = "?listtype=2"+ "&lon="
					+ geocoder.getLng() + "&lat=" + geocoder.getLat()
					+ "&pagenumber=" + pageNum + "&pagesize=" + pageSize;
			jsonString = HttpTools.getJsonContent(AppDataConfig.zufangUrl
					+ AppDataConfig.RenthouseList + sFilter);
			Log.e("JsonString", jsonString);
			rentHouseListResult = JsonTools.getRenthouseList(jsonString);
			getMoreData();
			if (rentHouseListResult.getSuccess()) {
				if (rentHouseListResult.getData().size() == 0) {
					msg.arg1 = 3;
				} else {
					msg.arg1 = 2;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = rentHouseListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			finish();
			break;
		case R.id.bt_positioning:
			// 定位+刷新
			showProgressBar();
			new Thread(getLocationAddressRun).start();// 定位
			break;
		case R.id.layout_constraint:
			// 跳转到定位条件选择页面
			Intent intent = new Intent(RentHouseLocalActivity.this,
					FilterPageActivity.class);
			startActivity(intent);
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(this, RentHouseDetailActivity.class);
		RenthouseList item= (RenthouseList) houseList.get((int) arg3);
		TextView text = (TextView) arg1.findViewById(R.id.un_house_id);
		intent.putExtra("houseId", text.getText().toString());
		intent.putExtra("tabNum", 3);
		intent.putExtra("renthouseList", item);
		historyService.saveRentHouse(item);
		startActivity(intent);

	}

}
